package com.itany.cloud.controller;

import com.itany.cloud.entity.User;
import com.itany.cloud.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author 石小俊
 */
@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    private static final String GLOBAL_URL = "http://localhost:8001/users";

    // 对于不同请求,访问方式也不同
    // get请求通过getForObject方法访问
    // <T> T getForObject(String url, Class<T> responseType, Object... uriVariables)
    // 参数一:提供服务的url地址
    // 参数二:服务返回的数据类型
    // 参数三:服务中需要的参数列表
    @GetMapping("/{id}")
    public ResponseResult findById(@PathVariable Integer id) {
        return restTemplate.getForObject(GLOBAL_URL + "/{id}", ResponseResult.class, id);
    }

    @GetMapping
    public ResponseResult findAll() {
        return restTemplate.getForObject(GLOBAL_URL, ResponseResult.class);
    }

    // post请求通过postForObject方法访问
    // 由于post请求参数传递方式与get请求不一样
    // 因此,此处需要指定参数
    // <T> T postForObject(String url, @Nullable Object request, Class<T> responseType, Object... uriVariables)
    @PostMapping
    public ResponseResult addUser(User user) {
        // 需要将所有请求参数按照键值对的方式存储到MultiValueMap中进行传递
        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        params.add("username", user.getUsername());
        params.add("password", user.getPassword());
        return restTemplate.postForObject(GLOBAL_URL, params, ResponseResult.class);
    }

    // 对于put请求与delete请求没有提供对应返回值
    // 因此可以使用通用方法exchange
    // 存在参数支持?传参
    // <T> ResponseEntity<T> exchange(String url, HttpMethod method, @Nullable HttpEntity<?> requestEntity, Class<T> responseType, Object... uriVariables)
    @PutMapping
    public ResponseResult modifyUser(User user) {
        String url = new StringBuffer()
                .append(GLOBAL_URL)
                .append("?id={id}")
                .append("&username={username}")
                .append("&password={password}")
                .toString();
        ResponseEntity<ResponseResult> entity = restTemplate.exchange(url, HttpMethod.PUT, null, ResponseResult.class, user.getId(), user.getUsername(), user.getPassword());
        return entity.getBody();
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteUser(@PathVariable Integer id) {
        ResponseEntity<ResponseResult> entity = restTemplate.exchange(GLOBAL_URL + "/{id}", HttpMethod.DELETE, null, ResponseResult.class, id);
        return entity.getBody();
    }
}
